import React from 'react';
import { Modal, info, success, FileUpload, Button, TitleBar, Checkbox } from '../../../ui-components';
import { connect } from 'react-redux'
import { TemplateMap, getFieldGroup }  from '../../../constants/fieldsMap'
import util from '../../../util';
import styleProfileUpload from '../../system/style.upload-profile'
/*import store from 'yields-store'*/
import Upload from 'component-upload'
import style from './style.hr-setting-import'
import cookie from 'component-cookie';

export default
@connect(({ system }) => ({ system }))
class HrProfileImport extends React.Component {

  state = {
    groups: [],
    checkedGroup: [],
    checked: [],
    step: 1,
    file: null,
    upload: null,
    error: '',
    number: '',
    dataError: false,
    dataErrorHandle: false,
    dataErrorHandleDone: false,
    requestHandleCSV: false,
    forbidden: false,
  }

  getUrl = (name) => `/users/roster/${name}`

  cancelForbidden() {
    this.setState({
      upload: null,
      error: '',
      file: null,
      number: '',
      checked: [],
      checkedGroup: [],
      forbidden: false
    })
  }

  handleUpload(file) {
    this.setState({
      file: file.file
    })
  }

  handleCSV() {
    this.props.manualHandleRosterCSV(this.CSVDocument, () => {
      this.setState({
        dataErrorHandleDone: true
      })
    })
    this.setState({
      requestHandleCSV: false
    })
  }

  upload() {
    const upload = new Upload(this.state.file)
    info('上传中...', true)
    upload.to({
      headers: {
        'X-Access-Token': cookie('X-Access-Token'),
        'X-Refresh-Token': cookie('X-Refresh-Token'),
      },
      path: this.getUrl('upload')
    })
    upload.on('progress', () => {})
    upload.on('end', res => {
      res = JSON.parse(res.responseText)
      if (/^2\d+$/.exec(res.code)) {
        success('上传成功!')
        this.setState({
          upload: true,
          number: res.data.totalCount
        })
      }

      else if ('4030000' == res.code) {
        info();
        this.setState({
          forbidden: true
        })
      }
      /*
      // 数据格式有误
      else if ('4000309' == res.code) {
        info()
        this.setState({
          upload: false,
          dataError: true
        })
        this.props.createDocument({ scenario: 3, documentName: this.state.file.name, storageStatus: 1 }, data => {
          const { documentId, presignedUrl } = data
          this.CSVDocument = documentId
          this.props.fileUpload({
            file: this.state.file,
            url: presignedUrl,
            cb: () => {
              this.setState({
                dataErrorHandle: true
              })
            }
          })
        })
      }
      */
      else {
        info()
        this.setState({
          upload: false,
          error: res.errorInfo || res.msg
        })
        this.props.createDocument({ scenario: 3, documentName: this.state.file.name, storageStatus: 1 }, data => {
          const { documentId, presignedUrl } = data
          this.CSVDocument = documentId
          this.props.fileUpload({
            file: this.state.file,
            url: presignedUrl,
            cb: () => {
              this.setState({
                dataErrorHandle: true
              })
            }
          })
        })
      }
    })
  }

  handleCheck(f, index, gIndex) {
    const { groups, checked, checkedGroup } = this.state
    if (~checkedGroup.indexOf(gIndex) || checked.some(cf => cf.referenceName == f.referenceName)) {
      this.setState({
        checkedGroup: checkedGroup.filter(i => i != gIndex),
        checked: checked.filter(cf => cf.referenceName != f.referenceName)
      })
    } else {
      this.setState({
        checked: [
          ...checked,
          {
            referenceName: f.referenceName,
            index,
            gIndex
          }
        ]
      }, () => {
        const g = groups.filter((g, i) => i == gIndex)[0];
        if (g.children.every(f => this.state.checked.some(cf => cf.referenceName == f.referenceName))) {
          this.setState({
            checkedGroup: [
              ...checkedGroup,
              gIndex
            ]
          })
        }
      })
    }
  }

  handleCheckGroup(gIndex) {
    const { checked, checkedGroup } = this.state
    if (~checkedGroup.indexOf(gIndex)) {
      this.setState({
        checkedGroup: checkedGroup.filter(i => i != gIndex),
        checked: checked.filter(cf => cf.gIndex != gIndex)
      })
    } else {
      this.setState({
        checkedGroup: [
          ...checkedGroup,
          gIndex
        ]
      })

      const { groups } = this.state
      const g = groups.filter((g, i) => i == gIndex)[0];
      let _checked = [
        ...checked
      ];
      for(let i = 0;i<g.children.length;i++) {
        const field = g.children[i];
        if (_checked.every(cf => cf.index != field.index)) {
          _checked = [
            ..._checked,
            {
              referenceName: field.referenceName,
              gIndex: field.gIndex,
              index: field.index
            }
          ]
        }
      }
      this.setState({
        checked: _checked
      })
    }
  }

  fetchCSV() {}

  componentDidMount() {
    this.props.fetchRosterAvailableFields();
  }

  componentWillUnmount() {
    this.props.resetSystem()
  }

  componentWillReceiveProps(props) {
    if (util.isNull(this.props.system.fields) && !util.isNull(props.system.fields)) {
      let index = 0;
      const { fields } = props.system
      const groups = getFieldGroup(TemplateMap, fields)
        .map(g => ({
          ...g,
          children: g.children.filter(f => f.isEnabled != 0 && !(f.isSystemRequired == 1 && f.isMandatory == 1) && f.importable !== false) 
        }))
        .filter(g => !util.isNull(g.children))
        .map((g, gIndex) => ({
          ...g,
          children: g.children.map(f => {
            return {
              ...f,
              index: index++,
              gIndex
            }
          })
        }))
      this.setState({
        groups
      })
    }
  }

  renderField(gIndex, f) {
    const { checkedGroup, checked } = this.state
    const active = ~checkedGroup.indexOf(gIndex) || checked.some(cf => cf.referenceName == f.referenceName)
    return (
      <Checkbox
        className={style.checkbox}
        onClick={this.handleCheck.bind(this, f, f.index, gIndex)}
        active={active}
        key={f.displayName}
        label={f.displayName}
      />
    );
  }

  renderGroups(groups) {
    if (util.isNull(groups)) return null;
    return (
      <div>
        { 
          groups.map((g, i) => (
            <div className={style.group} key={g.displayName}>
              <h3>{g.displayName}</h3>
              <div
                className={style.fields}
              >
                <Checkbox active={~this.state.checkedGroup.indexOf(i)} label="全选" onClick={this.handleCheckGroup.bind(this, i)} className={style.checkbox} />
                { g.children.map(this.renderField.bind(this, i)) }
              </div>
            </div>
          ))
        }
      </div>
    );
  }

  render() {

    const { groups } = this.state
    let actions
    if (this.state.upload !== null) {
      actions = () => (
        <div className={styleProfileUpload.actions}>
          {
            this.state.dataError? (
              !this.state.dataErrorHandleDone? (
                <Button 
                  disabled={!this.state.dataErrorHandle} 
                  label="授权人工处理" 
                  onClick={() => {
                    this.setState({ requestHandleCSV: true })
                  }}
                />
              ): null
            ): (
              <Button label="完成" onClick={() => {
                this.setState({
                  upload: null,
                  error: '',
                  file: null,
                  number: '',
                  checked: [],
                  checkedGroup: []
                })
              }}/>
            )
          }
        <Button blueLine label={this.state.upload? "继续上传": "重新上传"} onClick={() => {
          this.setState({
            checkedGroup: [],
            checked: [],
            upload: null,
            error: '',
            file: null,
            number: '',
            dataErrorHandle: false,
            dataError: false,
            dataErrorHandleDone: false
          })
        }}/>
        {
          (!this.state.upload && !this.state.dataErrorHandleDone) ?
          <Button 
            disabled={!this.state.dataErrorHandle} 
            label="授权人工处理" 
            onClick={() => {
              this.setState({ requestHandleCSV: true })
            }}
          />: null
        }
        </div>
      ) 
    }

    const titleBar = (
      <TitleBar
        label="补充花名册数据"
      />
    );

    if (this.state.upload) {
      return (
        <div>
          { titleBar }
          <div className={styleProfileUpload.body}>
            <div>
              <div className={styleProfileUpload['upload-success']}>上传成功，已成功导入{ this.state.number }名员工的档案</div>
              { actions? actions(): null }
            </div>
          </div>
        </div>
      )
    }

    // 数据格式有误
    if (this.state.dataError) {
      return (
        <div>
          { titleBar }
          <div className={styleProfileUpload.body}>
            <div>
              <div className={styleProfileUpload['upload-error']}>{ this.state.dataErrorHandleDone? '您已授权人工处理，请注意查收邮件，感谢您的耐心等待。': '因格式无法解析，数据上传失败，建议授权人工处理。'}</div>
              { actions? actions(): null }
            </div>
          </div>
          <Modal
            active={this.state.requestHandleCSV}
            onRequestClose={() => this.setState({ requestHandleCSV: false })}
            actions={[
              'cancel',
              ::this.handleCSV
            ]}
            title="授权人工处理"
          >
            <div>确认授权人工处理？格式校正后的 CSV 将发送到您的邮箱，您收到后可以重新上传。在此期间内请勿修改员工档案模板。</div>
          </Modal>
        </div>
      )
    }

    // 失败
    if (this.state.upload === false) {
      return (
        <div>
          { titleBar }
          <div className={styleProfileUpload.body}>
            <div>
              <div className={styleProfileUpload['upload-error']}>{ this.state.dataErrorHandleDone? '您已授权人工处理，请注意查收邮件，感谢您的耐心等待。': '上传或导入失败，此次导入花名册数据 0 个。请阅读提示，解决问题后重新上传。' }</div>
              <textarea disabled className={styleProfileUpload['error-info']} defaultValue={ this.state.error}/>
              { actions? actions(): null }
            </div>
          </div>
          <Modal
            active={this.state.requestHandleCSV}
            onRequestClose={() => this.setState({ requestHandleCSV: false })}
            actions={[
              'cancel',
              ::this.handleCSV
            ]}
            title="授权人工处理"
          >
            <div>确认授权人工处理？格式校正后的 CSV 将发送到您的邮箱，您收到后可以重新上传。</div>
          </Modal>
        </div>
      )
    }

    return (
      <div className={style.root}>
        { titleBar }
        <div className={style.body}>
          <div>
            <h2>1. 下载数据模板</h2>
            { this.renderGroups(groups) }

            <form action={this.getUrl('download')} method="post">
              <input type="hidden" name="X-Access-Token" value={cookie('X-Access-Token')}/>
              <input type="hidden" name="X-Refresh-Token" value={cookie('X-Refresh-Token')}/>
              {
                this.state.checked.length? <input name="referenceNames" value={this.state.checked.sort((a, b) => a.index > b.index).map(f => f.referenceName).join(',')} type="hidden" onChange={() => {}} />: null
              }
              <Button disabled={!this.state.checked.length} style={{ width: '233px', height: '40px', marginTop: '30px' }} label="点击下载表格模板（CSV）"/>
            </form>
          </div>
          <div>
            <h2>2. 上传填好的数据表</h2>
            <div className={styleProfileUpload.body}>
              <div className={styleProfileUpload['handle-template']}>
                <div>
                  <label>选择数据表（CSV）：</label>
                  <div style={{width: '100px', marginTop: '10px'}}>
                    <FileUpload
                      className={styleProfileUpload['pick-file']}
                      link
                      placeholder="选取文件"
                      onChange={::this.handleUpload}
                    />
                  </div>
                  <span>{ !this.state.file? '（未选择文件）': this.state.file.name }</span>
                </div>
              </div>
              {
                this.state.file? (
                  <Button 
                    onClick={::this.upload} 
                    className={styleProfileUpload['upload-button']} 
                    label="上传并导入数据" 
                    disabled={!this.state.file}
                  />
                ): null
              }
            </div>
          </div>
        </div>
        <Modal
          active={this.state.forbidden}
          onRequestClose={::this.cancelForbidden}
          actions={[
            ::this.cancelForbidden
          ]}
          title="提示"
        >
          <p>花名册数据中包含您本人的敏感信息，请删除本人所在的数据行后重新导入。</p>
        </Modal>
      </div>
    );
  }
}
